package com.dream.filter;

import com.dream.entity.ResponseResult;
import com.dream.util.JwtTokenUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class KaptchaAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private String processesUrl;

    public KaptchaAuthenticationFilter(String processesUrl, String failureUrl) {
        super(processesUrl);
        this.processesUrl = processesUrl;
        //重定向到获取验证码接口
        setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(failureUrl));
    }

    /**
     * 验证验证码过滤器
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        //如果是走登录/login，则验证验证码是否正确
        if ("POST".equalsIgnoreCase(req.getMethod()) && processesUrl.equals(req.getServletPath())) {
            //验证码可以存入到session中，也可以放到redis中,在这放入到session中
            String sessionKey = (String)req.getSession().getAttribute(JwtTokenUtils.KAPTCHA_SESSION_KEY);
            if (sessionKey == null || !sessionKey.equalsIgnoreCase(req.getParameter("sessionKey"))) {
                JwtTokenUtils.writeResponse(res,null, ResponseResult.fail("登录失败，验证码错误！"));
            }else {
                //清空session中的验证码
                req.getSession().removeAttribute(JwtTokenUtils.KAPTCHA_SESSION_KEY);
            }
        }
        chain.doFilter(request,response);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        return null;
    }
}
